<?php

namespace app\admin\service;

use app\admin\model\Examp;
use nxcsoft\excel\ExcelTools;
use think\facade\Db;

/**
 * 训练题库管理-服务类
 * @author 小码哥
 * @since 2020/11/15
 * Class ExampService
 * @package app\admin\service
 */
class ExampService extends BaseService
{
    /**
     * 构造函数
     * @author 小码哥
     * @since 2020/11/15
     * ExampService constructor.
     */
    public function __construct()
    {
        $this->model = new Examp();
    }

    /**
     * @return array
     * @throws \think\db\exception\DbException
     * 获取列表
     */
    public function getList()
    {
        $sort = 'id desc';
        // 常规查询条件
        $param = request()->param();
        $map = [];
        if ($param) {
            // 筛选标题
            if (isset($param['title']) && $param['title']) {
                $map[] = ['title', 'like', "%{$param['title']}%"];
            }
            if (isset($param['topic_id']) && $param['topic_id']) {
                $map[] = ['topic_id', '=', $param['topic_id']];
            }
            // 筛选状态
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
        }
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        $count = $this->model
            ->where($map)
            ->count();
        $ids = $this->model
            ->where($map)
            ->order($sort)
            ->page(PAGE, PERPAGE)
            ->column("id");
        $map[] = ['id', 'in', $ids];
        $field = '';
        $list = $this->model->getAllInfo($map, $field);
        if (empty($list)) {
            //获取数据总数
            //返回结果
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
                "count" => $count,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        } else {
            $prescript_ids = array_column($list, 'prescription_id');
            $topic_ids = array_column($list, 'topic_id');
            $prescriptInfo = Db::name('prescription')
                ->whereIn('id', $prescript_ids)
                ->field('id,title,problem_img')
                ->select()
                ->toArray();
            $topicInfo = Db::name('topic_data')
                ->whereIn('id', $topic_ids)
                ->field('id,title')
                ->select()
                ->toArray();
            foreach ($list as &$item) {
                $item['prescription_name'] = '';
                $item['problem_img'] = '';
                $item['topic_name'] = '';
                foreach ($prescriptInfo as $info) {
                    if ($item['prescription_id'] == $info['id']) {
                        $item['prescription_name'] = $info['title'];
                        $item['problem_img'] = $info['problem_img'];
                    }
                }
                foreach ($topicInfo as $topic) {
                    if ($item['topic_id'] == $topic['id']) {
                        $item['topic_name'] = $topic['title'];
                    }
                }
            }
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
                "count" => $count,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        }
        //获取数据总数
        //返回结果
    }

    /**
     * 添加或编辑
     * @return array
     * @since 2020/11/21
     * @author 小码哥
     */
    public function edit()
    { // 请求参数
        $data = request()->param();
        $id = request()->param('id');
        // 头像处理
        $initPrescriptionId = 0;
        if ($id) {
            $initPrescriptionId = Db::name('exam_problem')
                ->where('id', $id)
                ->value('prescription_id');
        }
        $res = parent::edit($data);
        $this->upProblemNum($data['prescription_id'], $initPrescriptionId);
        return $res; // TODO: Change the autogenerated stub
    }

    /**
     * 更新题库下的处方数量
     */
    public function upProblemNum($prescription_id, $initPrescriptionId)
    {
        if ($initPrescriptionId == 0) {
            $num = Db::name('exam_problem')
                ->where('prescription_id', $prescription_id)
                ->where('mark', 1)
                ->where('status', 1)
                ->count('*');
            Db::name('prescription')
                ->where('id', $prescription_id)
                ->update(['num' => $num]);
        } else {
            if ($prescription_id == $initPrescriptionId) {
                $num = Db::name('exam_problem')
                    ->where('prescription_id', $prescription_id)
                    ->where('mark', 1)
                    ->where('status', 1)
                    ->count('*');
                Db::name('prescription')
                    ->where('id', $prescription_id)
                    ->update(['num' => $num]);
            } else {
                $num = Db::name('exam_problem')
                    ->where('prescription_id', $prescription_id)
                    ->where('mark', 1)
                    ->where('status', 1)
                    ->count('*');
                $initTopicIdnum = Db::name('exam_problem')
                    ->where('mark', 1)
                    ->where('status', 1)
                    ->where('prescription_id', $initPrescriptionId)
                    ->count('*');
                Db::name('prescription')
                    ->where('id', $prescription_id)
                    ->update(['num' => $num]);
                Db::name('prescription')
                    ->where('id', $initPrescriptionId)
                    ->update(['num' => $initTopicIdnum]);
            }
            return;
        }

    }

    /**
     * 导入训练测试题库
     */
    public function import_examp_problem()
    {
        $params = request()->param();
        $this->checkboxProblem($params);
        $this->upchapterNum($params['prescription_id']);
        return message('导入成功', true);
    }

    /**
     * @param $prescription_id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 更新当前处方的题目数量
     */
    public function upchapterNum($prescription_id)
    {
        $problemNum = Db::name('exam_problem')
            ->where('prescription_id', $prescription_id)
            ->where('status', 1)
            ->count('*');
        Db::name('prescription')
            ->where('id', $prescription_id)
            ->update(['num' => $problemNum]);
    }

    /**
     * @param $params
     * @return array|bool
     * 导入多选选择题
     * 导入当前处方的题目总分不能超过该处方的最高分
     */
    public function checkboxProblem($params)
    {
        $prescription_id = $params['prescription_id'];
        $topic_id = $params['topic_id'];
        $status = $params['status'];
        //接受文件
        $file = $_FILES['file']['tmp_name'];
        //接受文件
        $indexArray = [
            'number',
            'type',
            'title',
            'A',
            'B',
            'C',
            'D',
            'E',
            'F',
            'G',
            'H',
            'I',
            'J',
            'score',
            'right_key',
        ];//title 数据库字段
        $resIndex = [
            'number',
            'type',
            'title',
            'score',
            'right_key',
        ];//必填字段0
        $obj = new ExcelTools();
        //对应关系 防止修改数据title
        $namesArray = [
            'number' => '序号',
            'type' => '题目类型',
            'title' => '题干',
            'A' => '选项A',
            'B' => '选项B',
            'C' => '选项C',
            'D' => '选项D',
            'E' => '选项E',
            'F' => '选项F',
            'G' => '选项G',
            'H' => '选项H',
            'I' => '选项I',
            'J' => '选项J',
            'score' => '分值',
            'right_key' => '正确答案',
        ];
        $res = $obj->SaveExcel($file, 1, $indexArray, $resIndex);
        foreach ($res[0] as $key => $value) {
            if ($namesArray[$key] != $value) {
                return message("数据格式不正确，请修改后提交", false, []);
            }
        }
        unset($res[0]);//删除表头信息
//        开始处理数据库
        $this->countPrescriptScore($res, $prescription_id, $topic_id);
        $typeArray = config('exam.exam_type');
        foreach ($res as $key => &$v) {
            $result = Db::name('exam_problem')
                ->where('title', $v['title'])
                ->where('mark', 1)
                ->where('topic_id', $topic_id)
                ->where('prescription_id', $prescription_id)
                ->value('id');
            if (empty($result)) {
                $peodata = [
                    'title' => $v['title'],
                    'right_key' => strtoupper(trim($v['right_key'])),
                    'score' => $v['score'],
                    'prescription_id' => $params['prescription_id'],
                    'type' => isset($typeArray[$v['type']]) ? $typeArray[$v['type']] : 9,
                    'topic_id' => $params['topic_id'],
                    'status' => $status,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                $proId = Db::name('exam_problem')->insertGetId($peodata);
                $asn = [
                ];
                if (!empty($v['A']) || strlen($v['A']) > 0) {
                    $asn[] =
                        [
                            'number' => 'A',
                            'problem_id' => $proId,
                            'content' => $v['A'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['B']) || strlen($v['B']) > 0) {
                    $asn[] =
                        [
                            'number' => 'B',
                            'problem_id' => $proId,
                            'content' => $v['B'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['C']) || strlen($v['C']) > 0) {
                    $asn[] =
                        [
                            'number' => 'C',
                            'problem_id' => $proId,
                            'content' => $v['C'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['D']) || strlen($v['D']) > 0) {
                    $asn[] =
                        [
                            'number' => 'D',
                            'problem_id' => $proId,
                            'content' => $v['D'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['E']) || strlen($v['E']) > 0) {
                    $asn[] =
                        [
                            'number' => 'E',
                            'problem_id' => $proId,
                            'content' => $v['E'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['F']) || strlen($v['F']) > 0) {
                    $asn[] =
                        [
                            'number' => 'F',
                            'problem_id' => $proId,
                            'content' => $v['F'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['G']) || strlen($v['G']) > 0) {
                    $asn[] =
                        [
                            'number' => 'G',
                            'problem_id' => $proId,
                            'content' => $v['G'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['H']) || strlen($v['H']) > 0) {
                    $asn[] =
                        [
                            'number' => 'H',
                            'problem_id' => $proId,
                            'content' => $v['H'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['I']) || strlen($v['I']) > 0) {
                    $asn[] =
                        [
                            'number' => 'I',
                            'problem_id' => $proId,
                            'content' => $v['I'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                if (!empty($v['J']) || strlen($v['J']) > 0) {
                    $asn[] =
                        [
                            'number' => 'J',
                            'problem_id' => $proId,
                            'content' => $v['J'],
                            'type' => 2,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                }
                Db::name('answer')->insertAll($asn);
            }
        }
        return true;
    }

    /**
     * 统计该处方的总分数
     */
    public function countPrescriptScore($res, $prescription_id, $topic_id)
    {
        $newscore = array_column($res, 'score');
        $newscore = array_sum($newscore);
        $where = [
            'prescription_id' => $prescription_id,
            'topic_id' => $topic_id,
            'mark' => 1,
        ];
        $score = Db::name('exam_problem')
            ->where($where)
            ->sum('score');
        $allscore = $newscore + $score;
        if ($allscore > 0) {
            return message("该处方题目累计分值超出规定值", false, []);
        }

    }
}